package com.sunday.volunteer.fragment.tab;

        import android.Manifest;
        import android.content.Intent;
        import android.content.pm.PackageManager;
        import android.graphics.Bitmap;
        import android.graphics.Canvas;
        import android.graphics.Color;
        import android.graphics.Paint;
        import android.graphics.PorterDuff;
        import android.os.Build;
        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
        import android.provider.Settings;
        import android.support.annotation.Nullable;
        import android.text.TextUtils;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.LinearLayout;
        import android.widget.TextView;

        import com.baidu.location.BDLocation;
        import com.baidu.location.BDLocationListener;
        import com.baidu.mapapi.map.BaiduMap;
        import com.baidu.mapapi.map.BitmapDescriptor;
        import com.baidu.mapapi.map.BitmapDescriptorFactory;
        import com.baidu.mapapi.map.MapStatusUpdateFactory;
        import com.baidu.mapapi.map.MapView;
        import com.baidu.mapapi.map.Marker;
        import com.baidu.mapapi.map.MarkerOptions;
        import com.baidu.mapapi.map.OverlayOptions;
        import com.baidu.mapapi.model.LatLng;
        import com.bumptech.glide.Glide;
        import com.bumptech.glide.request.animation.GlideAnimation;
        import com.bumptech.glide.request.target.SimpleTarget;
        import com.sunday.common.model.ResultDO;
        import com.sunday.common.utils.Constants;
        import com.sunday.common.utils.DeviceUtils;
        import com.sunday.common.utils.ToastUtils;
        import com.sunday.common.widgets.UIAlertView;
        import com.sunday.member.base.BaseFragment;
        import com.sunday.member.utils.SharePerferenceUtils;
        import com.sunday.volunteer.BaseApp;
        import com.sunday.volunteer.R;
        import com.sunday.volunteer.entity.Activity;
        import com.sunday.volunteer.http.HttpClient;
        import com.sunday.volunteer.ui.MainActivity;
        import com.sunday.volunteer.utils.BaseUtil;

        import java.util.ArrayList;
        import java.util.List;

        import butterknife.Bind;
        import butterknife.ButterKnife;
        import butterknife.OnClick;
        import retrofit2.Call;
        import retrofit2.Callback;
        import retrofit2.Response;

        import static com.sunday.volunteer.R.id.bitmap;
        import static com.sunday.volunteer.R.id.num;
        import static com.sunday.volunteer.R.id.re;

/**
 * Created by Pual's PC on 2016/10/8.
 */
public class IndexMapFragment extends BaseFragment {

    @Bind(R.id.map_view)
    MapView mapView;
    @Bind(R.id.image_view)
    ImageView imageView;
    @Bind(bitmap)
    View viewBitmap;
    @Bind(R.id.item)
    View item;

    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.count)
    TextView count;
    @Bind(R.id.group_name)
    TextView group_name;
    @Bind(R.id.hours)
    TextView hours;
    @Bind(R.id.map_view_bg)
    View map_view_bg;

    private List<Activity> list = new ArrayList<>();
    private BaiduMap baiduMap;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index_map, null);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        item.setVisibility(View.GONE);
        baiduMap = mapView.getMap();

        //addMarker();
        latitude = Double.valueOf(SharePerferenceUtils.getIns(mContext).getString(Constants.LATITUDE, "0"));
        longitude =Double.valueOf(SharePerferenceUtils.getIns(mContext).getString(Constants.LONGITUDE, "0"));
        setData(latitude , longitude);

    }

    private double latitude ;
    private double longitude;

    private void setData(double latitude , double longitude){
        //定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);
        baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLngZoom(point , 16));
        getData();
    }

//    @OnClick(R.id.image_view)
//    void add(){
//        bitmapList.clear();
//        addMarker(list.get(0).getMainImage() ,0.09);
//    }


    public void getData() {
        Call<ResultDO<List<Activity>>> call = HttpClient.getHttpAdapter().getActivitys(BaseApp.getInstance().getMemberId(), 1, 2000, null, null, null);
        call.enqueue(new Callback<ResultDO<List<Activity>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Activity>>> call, Response<ResultDO<List<Activity>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    list.addAll(response.body().getResult());
                    saveBitmap();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Activity>>> call, Throwable t) {

            }
        });

    }

    private List<Bitmap> bitmaps = new ArrayList<>();
    private void saveBitmap(){
        if(list.size() != 0){
            Glide.with(mContext).load(list.get(bitmaps.size()).getGroupImage()).asBitmap().into(target);
        }
    }

    private SimpleTarget target = new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
            bitmaps.add(bitmap);
            if(bitmaps.size() < list.size()){
                Glide.with(mContext).load(list.get(bitmaps.size()).getGroupImage()).asBitmap().into(target);
            }else {
                addMarker(-1);
            }
        }
    };




    private List<BitmapDescriptor> bitmapList = new ArrayList<>();

    private List<LatLng> latLngs = new ArrayList<>();
    private void addMarker( int kk) {
        bitmapList.clear();
        baiduMap.clear();

        List<OverlayOptions> options = new ArrayList<>();
        for(int i=0 ;i<bitmaps.size() ;i++){
            map_view_bg.setVisibility(kk == i?View.VISIBLE:View.GONE);
            imageView.setImageBitmap(bitmaps.get(i));
            Bitmap bitmap = convertViewToBitmap(viewBitmap);
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
            bitmapList.add(bitmapDescriptor);
            LatLng point;
            if(latLngs.size() < bitmaps.size()){
                double a =(Math.random()*18-9)/1000;
                double b =(Math.random()*18-9)/1000;
                point = new LatLng(latitude +a, longitude+b);
                latLngs.add(point);
            }else {
                point = latLngs.get(i);
            }

            OverlayOptions option = new MarkerOptions().position(point).icon(bitmapDescriptor);
            options.add(option);
            baiduMap.addOverlay(option);
        }
        baiduMap.removeMarkerClickListener(onclick);
        baiduMap.setOnMarkerClickListener(onclick);
    }

    private BaiduMap.OnMarkerClickListener onclick = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            for( int i = 0; i< bitmapList.size(); i++){
                if(bitmapList.get(i) == marker.getIcon()){
                    Activity item = list.get(i);
                    BaseUtil.setText(name, item.getName());
                    BaseUtil.setText(time, item.getTime());
                    BaseUtil.setText(address, item.getAddress());
                    BaseUtil.setText(count, item.getJoinNumber() + "人");
                    BaseUtil.setText(hours, String.format("时长 %.0f%s", item.getHours(), "h"));
                    BaseUtil.setText(group_name, String.format("来自 %s", item.getGroupName()));
                    addMarker(i);
                }
            }
            item.setVisibility(View.VISIBLE);
            return true;
        }
    };

    //将view转bitmap
    public Bitmap convertViewToBitmap(View view){

        Bitmap bitmap = Bitmap.createBitmap(120, 120 ,
                Bitmap.Config.ARGB_8888);
        //利用bitmap生成画布
        Canvas canvas = new Canvas(bitmap);

        //把view中的内容绘制在画布上
        view.draw(canvas);
        return bitmap;
    }


    @OnClick(R.id.left_img)
    void leftImg() {
        ((MainActivity) getActivity()).setPager(0);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if(mapView != null){
            mapView.onDestroy();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }


}
